package com.tanhua.manager.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.manager.service.AdminService;
import org.json.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @GetMapping("/verification")
    public void showVerificationImage(HttpServletResponse response, String uuid) throws IOException {
        //设置浏览器禁止使用缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");


        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(288, 97);

        String code = captcha.getCode();
        adminService.cacheCode(code, uuid);
        captcha.write(response.getOutputStream());
    }

    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String code = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        return adminService.login(username, password, code, uuid);
    }

    @PostMapping("/profile")
    public ResponseEntity profile() {
        return adminService.profile();
    }

    @PostMapping("/logout")
    public ResponseEntity logout() {
        return adminService.logout();
    }

}
